package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.RpcMsgLog;
import com.ruoyi.system.domain.SysCompanyThingsboard;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.mapper.RpcMsgLogMapper;
import com.ruoyi.system.service.IRpcMsgLogService;
import com.ruoyi.system.service.IThingsBoardTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@Service
public class RpcMsgLogServiceImpl implements IRpcMsgLogService {
    @Autowired
    private RpcMsgLogMapper rpcMsgLogMapper;

    @Autowired
    private IThingsBoardTenantService thingsBoardTenantService;

    @Override
    public void saveFailureRpcReques(String deviceId, JSONObject requestBody, SysCompanyThingsboard sysCompanyThingsboard) {
        try {
            RpcMsgLog rpcMsgLog = new RpcMsgLog();
            rpcMsgLog.setCompanyId(sysCompanyThingsboard.getCompanyId());
            rpcMsgLog.setDeviceId(deviceId);
            rpcMsgLog.setRequestBody(requestBody.toJSONString());
            rpcMsgLog.setStatus(1);
            rpcMsgLog.setErrorTimes(0);
            rpcMsgLog.setTbUsername(sysCompanyThingsboard.getTbUsername());
            rpcMsgLog.setTbPassword(sysCompanyThingsboard.getTbPassword());
            rpcMsgLogMapper.insertRpcMsgLog(rpcMsgLog);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    @Override
    public boolean exeRpcReques(Long id) {
        boolean b = true;
        RpcMsgLog rpcMsgLog = getModeById(id);
        if (null == rpcMsgLog) {
            throw new RuntimeException("未找到对应的请求记录");
        }
        rpcMsgLog.setUpdatedTime(new Date());
        try {
            thingsBoardTenantService.exeRpcRequest(rpcMsgLog);
            rpcMsgLog.setStatus(0);
        } catch (Exception e) {
            log.info("", e);
            rpcMsgLog.setStatus(1);
            rpcMsgLog.setErrorTimes(rpcMsgLog.getErrorTimes() + 1);
            b = false;
        }
        rpcMsgLogMapper.updateNotNullByPrimaryKeySelective(rpcMsgLog);
        return b;
    }

    @Override
    public List<RpcMsgLog> queryPage(QueryVo queryVo) {
        return rpcMsgLogMapper.query4List(queryVo);
    }

    public RpcMsgLog getModeById(Long id) {
        QueryVo vo = new QueryVo();
        vo.getFilters().put("id", id);
        List<RpcMsgLog> ll = rpcMsgLogMapper.queryList(vo);
        if (CollectionUtils.isEmpty(ll)) {
            return null;
        }
        return ll.get(0);
    }
}
